package usi.ch.onto.common;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;

public class ConcatenateRDFS {
	private String workDirectory;
	
	private String destinationFile;

	public ConcatenateRDFS(String workDirectory, String destinationFile){
		this.workDirectory = workDirectory;
		this.destinationFile = destinationFile;
	}
	
	
	private int NUMBER_INITIAL_LINES_IGNORE = 7;
	/**
	 * simple method
	 * processes all files in folder
	 * ignores the first 7 lines
	 * assumes the last line is </rdf:RDF> and has nothing important in that line
	 * 
	 * this can be improved with an XML parser
	 */
	public void process() throws Exception{
		File destination = new File(destinationFile);
		if (destination.exists())
			throw new Exception(destinationFile + " already exists!");
		
		File dir = new File(workDirectory);
		// table name is the name of the directory
		if (dir.isDirectory() == false)
			throw new Exception(workDirectory + " does not point to a directory");

	   File[] fileList =  dir.listFiles();
	   BufferedWriter out = new BufferedWriter(new FileWriter(destination));
	   writeHeader(out);
	   BufferedReader br; String line;
		for (File file : fileList) {
			if (file.isDirectory())
				continue;
			System.out.print(".");			
			br = new BufferedReader(new FileReader(file));
			try{
				//ignore lines
				for(int i = 0; i < NUMBER_INITIAL_LINES_IGNORE; i++)
					br.readLine();
			}catch (Exception ex){}
			
			while((line = br.readLine()) != null){
				
				if (line.contains("</rdf:RDF>"))
					break;
				out.write(line);
				out.newLine();
			}
			out.flush();
			br.close();
		}
		
		writeFooter(out);
		out.close();
		System.out.println("done");
	}
	
	private void writeHeader(BufferedWriter outFile) throws IOException{
		outFile.write("<?xml version=\"1.0\"?>"); outFile.newLine();
		outFile.write("<!DOCTYPE rdf:RDF [<!ENTITY d \"http://www.w3.org/2001/XMLSchema#\">"); outFile.newLine();
		outFile.write("                   <!ENTITY y \"http://www.mpii.de/yago/resource/\">]>"); outFile.newLine();
		outFile.write("<rdf:RDF xmlns:rdf=\"http://www.w3.org/1999/02/22-rdf-syntax-ns#\""); outFile.newLine();
		outFile.write("         xml:base=\"http://www.mpii.de/yago/resource\""); outFile.newLine();
		outFile.write("         xmlns:rdfs=\"http://www.w3.org/2000/01/rdf-schema#\""); outFile.newLine();
		outFile.write("         xmlns:y=\"http://www.mpii.de/yago/resource/\">"); outFile.newLine();
	}
	
	private void writeFooter(BufferedWriter outFile) throws IOException{
		outFile.write("</rdf:RDF>");
		outFile.newLine();
	}
}
